<?php
/**
 * Lightweight game bootstrap and dispatcher
 *
 * @author Matt Pike
 */
class GameBootstrap extends Bootstrap{

	public function __construct(){
		require_once("SiteConfig.php");
		require_once("GameConfig.php");
		$this->loadCoreResources();
		$this->dispatchRequest($_REQUEST);
	}

	/**
	 * Dispatch Request To Releveant Controller+Action
	 *
	 * @return string
	 */
	public function dispatchRequest(array $request){
		$isAjax = Request::isAjaxRequest();

		$controller = Request::getWord("c",null,$request);
		$action 	= Request::getWord("a",null,$request);

		try{
			if(!$controller || !$action){
				throw new BadRequest("Invalid controller/action: c=$controller a=$action");
			}

			if($this->loadController($controller) && $this->actionExists($controller,$action)){
				if($isAjax){
					echo json_encode($this->callAction($controller, $action, $request));
				}else{
					echo $this->callAction($controller, $action, $request);
				}
				exit;
			}else{
				throw new BadRequest("Unrecognised controller: ".$controller);
			}
		}catch(Exception $e){
			// @todo add user friendly messaages and error codes to all exceptions we we're not returning actual errors
			if($isAjax){
				return json_encode(array("err"=>print_r($e,true)));
			}else{
				print_r($e);
			}
		}
	}
}